package framework.utils;

import framework.controller.*;
import framework.event.CustomEvent;
import framework.utils.dto.ActionCommand;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.RunnableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version 0.5
 * @author Michel Jansma
 * Class for handling incoming COMMANDS
 */
public class CommandListener implements Runnable {
	
	private boolean running = true;
	
	//All commands which can be handled
	public String[] COMMANDS = new String[] {
		"CHALLENGE", "GAMELIST", 
		"PLAYERLIST", "MATCH", 	 
		"MOVE", "YOURTURN", 
		"WIN", "LOSS", 	 
		"OK", "ERR"
	};
	
	public CommandListener() {};
	
	public void run() {
		while(this.running) {
			while(!ServerController._STACK.isEmpty()) {
				this.commandListener();
			};
		};
	};
	
	private void commandListener() {
		//POP value from stack
		ActionCommand command = ServerController._STACK.removeFirst();
		//Call action performed from current listener
		ServerController.CURRENT_LISTENER.actionPerformed(new CustomEvent(
			ServerController.CURRENT_LISTENER, 
			command.getCommand() != null ? command.getCommand() : this.getCommand(command.getLine()), 
			this.setList(command.getLine())
		));
	};
	
	private String getCommand(String line) {
		for(String command : this.COMMANDS) {
			if(line.indexOf(command) != -1) {
				return command;
			};
		};
		return "";
	};
	
	/**
	 * GameServer line to list
	 * @method setList
	 * @param <String> line 
	 * @return <ArrayList<String>> list
	 */
	private ArrayList<String> setList(String line) {
		//line = line.toUpperCase();
		Pattern pattern 	   = Pattern.compile("\"[\\d\\w\\s,.]+\"");
		Matcher matches 	   = pattern.matcher(line);
		ArrayList<String> list = new ArrayList<String>();
		while(matches.find()) {
			list.add(matches.group().replace("\"", ""));
		}
		return list;
	};

}
